import React, { useEffect, useRef } from 'react';
import { Box, Typography } from '@mui/material';

const AMapComponent = React.memo(({ onMapReady }) => {
  const mapContainerRef = useRef(null);
  const mapInstanceRef = useRef(null);
  const scriptRef = useRef(null);
  const [isLoading, setIsLoading] = React.useState(true);

  useEffect(() => {
    // 安全密钥配置
    window._AMapSecurityConfig = {
      securityJsCode: '78dd983411a264c1fba50fbaaf6c3455'
    };

    const initMap = () => {
      if (!window.AMap || mapInstanceRef.current) return;

      const mapInstance = new window.AMap.Map(mapContainerRef.current, {
        zoom: 13,
        center: [116.397428, 39.90923],
        viewMode: '3D',
        pitch: 35,
        resizeEnable: true
      });

      mapInstanceRef.current = mapInstance;
      setIsLoading(false);
      onMapReady(mapInstance);
    };

    const loadScript = () => {
      if (!window.AMap && !scriptRef.current) {
        scriptRef.current = document.createElement('script');
        scriptRef.current.src = 'https://webapi.amap.com/maps?v=2.0&key=820e2129ccdd2f2b54ea65a8999c3196&plugin=AMap.ToolBar,AMap.Scale,AMap.MapType,AMap.Geolocation';
        scriptRef.current.async = true;
        scriptRef.current.onload = initMap;
        document.body.appendChild(scriptRef.current);
      } else {
        initMap();
      }
    };

    loadScript();

    return () => {
      if (mapInstanceRef.current) {
        mapInstanceRef.current.destroy();
        mapInstanceRef.current = null;
      }
      if (scriptRef.current && document.body.contains(scriptRef.current)) {
        document.body.removeChild(scriptRef.current);
        scriptRef.current = null;
      }
      // 清除全局变量
      delete window.AMap;
      delete window._AMapSecurityConfig;
    };
  }, [onMapReady]);

  return (
    <Box
      ref={mapContainerRef}
      sx={{
        height: '400px',
        mb: 3,
        bgcolor: 'grey.100',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center'
      }}
    >
      {isLoading && <Typography>地图加载中...</Typography>}
    </Box>
  );
});

export default AMapComponent; 